<template>
    <div class="flowCanvas">
        <div class="container" ref="container"></div>
        <!-- 节点面板 -->
        <CustomNodePanel v-if="lf" :lf="lf"></CustomNodePanel>
        <!-- 数据面板 -->
        <BpmnDataPanel v-if="lf" :lf="lf"></BpmnDataPanel>
        <!-- 弹窗编辑 -->
        <el-drawer title="编辑节点" :modal="false" v-model="drawer" :direction="'rtl'">
            <div v-if="currentNode">节点ID: {{ currentNode.data.id }}</div>
            <div v-if="currentNode">节点名称:<input v-model="nodeText"> </div>          
            <div v-show="selectedType === '' || selectedType === 'role'">角色名称: <el-select 
                    v-model="selectedValue" 
                    placeholder="选择角色" 
                    size="large" 
                    style="width: 240px" 
                    clearable
                    @change="onRoleChange">
                    <el-option v-for="item in roleOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select></div>
            <div v-show="selectedType === '' || selectedType === 'department'">部门名称: <el-select 
                    v-model="selectedValue" 
                    placeholder="选择部门" 
                    size="large" 
                    style="width: 240px" 
                    clearable
                    @change="onDepartmentChange">
                    <el-option v-for="item in departmentOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select></div>
            <div v-show="selectedType === '' || selectedType === 'user'">用户名称: <el-select 
                    v-model="selectedValue" 
                    placeholder="选择用户" 
                    size="large" 
                    style="width: 240px" 
                    clearable
                    @change="onUserChange">
                    <el-option v-for="item in userOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select></div>

            <div>


                <button type="button" @click="handlerSetPropValue">保存</button>
            </div>
        </el-drawer>
    </div>
</template>

<script>
import LogicFlow from "@logicflow/core";
import "@logicflow/core/dist/index.css";
import * as roleApi from '../../api/role'
import * as userApi from '../../api/user'
import * as departmentApi from '../../api/department'
import {
    BpmnElement,
    BpmnXmlAdapter,
    Snapshot,
    Control,
    Menu,
    SelectionSelect,
} from "@logicflow/extension";
import "@logicflow/extension/lib/style/index.css";
import CustomNodePanel from "./components/CustomNodePanel.vue";
import BpmnDataPanel from "./components/BpnmDataPanel.vue";
import { ElMessage } from 'element-plus'
import router from "@/router";
export default {
    name: "logicflowCustom",
    data() {
        return {
            lf: null,
            drawer: false,
            currentNode: null,
            nodeText: '',
            // 统一的选择值
            selectedValue: '',        // 存储选中的值
            selectedType: '',         // 存储选中的类型：'role', 'department', 'user'
            // 角色相关
            roleOptions: [],
            roleList: [],
            // 用户相关
            userOptions: [],
            userList: [],
            // 部门相关
            departmentOptions: [],
            departmentList: [],
            tableLoading: false,
            pagination: {
                currentPage: 1,
                pageSize: 10,
                total: 0
            }
        };
    },
    components: { CustomNodePanel, BpmnDataPanel },

    mounted() {
        this.loadRoleList();
        this.loadUserList();
        this.loadDepartmentList();
        LogicFlow.use(BpmnElement);
        LogicFlow.use(BpmnXmlAdapter);
        LogicFlow.use(Snapshot);
        LogicFlow.use(Control);
        LogicFlow.use(Menu);
        LogicFlow.use(SelectionSelect);
        //初始化
        this.lf = new LogicFlow({
            container: this.$refs.container,
            grid: {
                size: 10,
                visible: true,
                type: "mesh",
                config: {
                    color: "#ababab",
                    thickness: 1,
                },
            },
        });
        this.lf.render();
        //绑定事件
        const { eventCenter } = this.lf.graphModel;

        this.bindEvent(eventCenter);

        const graphData = this.lf.getGraphData();
        console.log("流程图完整数据：", graphData);
    },

    methods: {
        /**
         * 加载角色列表
         * 根据搜索条件和分页参数获取角色数据
         */
        async loadRoleList() {
            try {
                this.tableLoading = true;
                const response = await roleApi.getRoleList({
                    page: this.pagination.currentPage,
                    size: this.pagination.pageSize
                });

                if (response.data.code === 200) {
                    this.roleList = response.data.data.list || [];
                    this.roleOptions = this.roleList.map(role => ({
                        value: role.roleName,
                        label: role.roleName
                    }));
                } else {
                    ElMessage.error(response.data.message || '加载角色列表失败');
                }
            } catch (error) {
                ElMessage.error('加载角色列表失败');
                console.error('加载角色列表失败:', error);
            } finally {
                this.tableLoading = false;
            }
        },
        /**
         * 加载用户列表
         * 根据搜索条件和分页参数获取用户数据
         */
        async loadUserList() {
            try {
                this.tableLoading = true;
                const response = await userApi.getUserList({
                    page: this.pagination.currentPage,
                    size: this.pagination.pageSize
                });

                if (response.data.code === 200) {
                    this.userList = response.data.data.list || [];
                    this.userOptions = this.userList.map(user => ({
                        value: user.userNickname,
                        label: user.userNickname
                    }));
                    this.pagination.total = response.data.data.count || 0;
                } else {
                    ElMessage.error(response.data.message || '加载用户列表失败');
                }
            } catch (error) {
                ElMessage.error('加载用户列表失败');
                console.error('加载用户列表失败:', error);
            } finally {
                this.tableLoading = false;
            }
        },
        /**
         * 加载部门列表
         * 根据搜索条件和分页参数获取部门数据
         */
        async loadDepartmentList() {
            try {
                this.tableLoading = true;
                const response = await departmentApi.getDepartmentList({
                    page: this.pagination.currentPage,
                    size: this.pagination.pageSize
                });

                if (response.data.code === 200) {
                    this.departmentList = response.data.data.list || [];
                    this.departmentOptions = this.departmentList.map(dept => ({
                        value: dept.departmentName,
                        label: dept.departmentName
                    }));
                    this.pagination.total = response.data.data.count || 0;
                } else {
                    ElMessage.error(response.data.message || '加载部门列表失败');
                }
            } catch (error) {
                ElMessage.error('加载部门列表失败');
                console.error('加载部门列表失败:', error);
            } finally {
                this.tableLoading = false;
            }
        },
        // 角色选择变化处理
        onRoleChange(value) {
            if (value) {
                this.selectedType = 'role';
                this.selectedValue = value;
            } else {
                this.selectedType = '';
                this.selectedValue = '';
            }
        },
        // 部门选择变化处理
        onDepartmentChange(value) {
            if (value) {
                this.selectedType = 'department';
                this.selectedValue = value;
            } else {
                this.selectedType = '';
                this.selectedValue = '';
            }
        },
        // 用户选择变化处理
        onUserChange(value) {
            if (value) {
                this.selectedType = 'user';
                this.selectedValue = value;
            } else {
                this.selectedType = '';
                this.selectedValue = '';
            }
        },
        bindEvent(eventCenter) {
            // 使用 mousedown 事件来触发弹窗
            eventCenter.on("node:mousedown", (args) => {
                // 检查args是否有效
                if (!args || !args.data) {
                    console.error("节点点击事件参数无效:", args);
                    return;
                }
                
                this.currentNode = args;
                this.drawer = true;
               
                // 加载节点文本
                this.nodeText = this.currentNode.data.text ? this.currentNode.data.text.value : '';
                
                // 加载已保存的属性值
                const properties = this.currentNode.data.properties || {};
                this.selectedValue = properties.selectedValue || '';
                this.selectedType = properties.selectedType || '';
            });
        },
        handlerSetPropValue() {
            // 检查currentNode是否存在
            if (!this.currentNode) {
                ElMessage.error('没有选中的节点');
                return;
            }
            
            // 保存统一的选择值和类型
            this.lf.setProperties(this.currentNode.data.id, {
                selectedValue: this.selectedValue,    // 选中的值
                selectedType: this.selectedType,      // 选中的类型
                PropValue: this.selectedValue         // 保持向后兼容
            });
            
            // 更新节点文本
            this.lf.graphModel.updateText(this.currentNode.data.id, this.nodeText);
            
            // 关闭抽屉
            this.drawer = false;
            router.q
            // 显示保存成功消息
            ElMessage.success('节点属性保存成功');
            
            // 获取当前流程图的所有数据（节点、连线等）
            const graphData = this.lf.getGraphData();
            console.log("更新后的流程图数据：", graphData);
        }

    },
};

</script>

<style>
.flowCanvas {
    position: relative;
    width: 100%;
    height: 100vh;
    margin: 0px;
    display: flex;
}

.flowCanvas .container {
    display: flex;
    flex-grow: 1;
    /*铺满剩余空间*/
    border: 3px solid #ababab;
    overflow: hidden;
}
</style>